package com.dao;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import util.DBUtil;

import com.bean.User;

public class UserDao {
	String sql =" ";
	ResultSet rs = null;
	
	public int addUser(User user){
		sql = "insert into user values(?,?)";
		int i = 0;
		Object[] values = new Object[]{user.getUsername(),user.getPassword()};
		
		try{
			DBUtil.getConnection();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		try{
			i = DBUtil.executeUpdate(sql,values);
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			DBUtil.close();
		}
		return i;
	}
	
	public int loginByUser(User user){
		sql = "select * from user where username='"+user.getUsername()+"'";
		int i = 0;
		try {
			DBUtil.getConnection();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		rs = DBUtil.executeQuery(sql);
		try{
			if (rs.next()) {
				String password = rs.getString("password");
				if(user.getPassword().equals(password)){
					i = 1;
				}else{
					i = 0;
				}
			}else{
				i = -1;
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			DBUtil.close();
		}
		return i;
	}
	public int  ByUser(User user){
		sql = "select * from user where username='"+user.getUsername()+"'";
		int i = 0;
		try {
			DBUtil.getConnection();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		rs = DBUtil.executeQuery(sql);
		try{
			if (rs.next()) {
				String password = rs.getString("password");
				if(user.getPassword().equals(password)){
					i = 1;
				}else{
					i = 0;
				}
			}else{
				i = -1;
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			DBUtil.close();
		}
		return i;
	}
	public int updateUser2(User user){
		int i = 0;
		String sql = "update user set password=? where username=?";
		Object[] values = new Object[]{user.getPassword(),user.getUsername()};
		try{
			DBUtil.getConnection();
			i = DBUtil.executeUpdate(sql, values);
		} catch(Exception e){
			e.printStackTrace();
		} finally{
			DBUtil.close();
		}
		return i;
	}
	public int selectByUser(User user){
		return 0;
	}
	
}
